package com.ctos.common;

import com.ctos.Exception.CustomException;
import com.ctos.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理sql异常
     * @param sq
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result doException(SQLIntegrityConstraintViolationException sq){
        log.info(sq.getMessage());
        if (sq.getMessage().contains("Duplicate entry")){
            String[] split = sq.getMessage().split(" ");

            return Result.error(split[2]+"已存在，请重试。");
        }
        return Result.error("未知错误");
    }

    /**
     * 处理自定义异常
     * @param ce
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result doException(CustomException ce){
        log.info(ce.getMessage());
        return Result.error(ce.getMessage());
    }

}
